package com.situ.crm.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.situ.crm.common.Constants;
import com.situ.crm.common.util.SessionUtil;
import com.situ.crm.entity.User;
import com.situ.crm.service.IUserService;

@Controller
@RequestMapping(value = "/")
public class LoginController {

	@Autowired
	private IUserService userService;

	// 打开登录页面
	@GetMapping(value = "/login")
	public String openLoginPage() {
		return "login";
	}

	// 接收用户名密码 做登录
	@PostMapping(value = "/login")
	public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
		User user = userService.doLogin(username, password);
		if (user == null) {
			return "login";
		}
		SessionUtil.getSession().setAttribute(Constants.SESSION_CURRENT_KEY, user);
		return "redirect:/index";
	}

	// 用户退出登录
	@GetMapping(value = "/logout")
	public String doLogout() {
		SessionUtil.getSession().removeAttribute(Constants.SESSION_CURRENT_KEY);
		return "redirect:/login";
	}

	// 处理国际化切换
	@GetMapping(value = "/i18n")
	public String i18n(String language, HttpServletRequest request) {
		if (language.equals("en")) {
			request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US"));
		}
		if (language.equals("zh")) {
			request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("zh", "CN"));
		}
		return "redirect:/login";
	}

}
